package com.ruoyi.algorithm.util.harbor;

import com.beihu.sightplus.common.response.ErrorMsgType;
import com.beihu.sightplus.common.response.ResultData;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

/**
 * @author dyk
 * @date 2021/7/8 16:24
 * @description
 */
public class HttpUtils {

    /**
     * 发送带auth post请求
     *
     * @param url      url
     * @param map      data
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    public static ResultData sendPost(String url, Map<String, Object> map, String userName, String password) {
        HttpHeaders requestHeaders = new HttpHeaders();
        String authString = userName + ":" + password;
        byte[] authEncBytes = new byte[0];
        try {
            authEncBytes = Base64.getEncoder().encode(authString.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String authStringEnc = new String(authEncBytes);
        requestHeaders.add("Authorization", "Basic " + authStringEnc);
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
        RestTemplate restTemplate = new RestTemplate();
        int rawStatusCode = 200;
        String result;
        try {
            result = restTemplate.postForObject(url, new HttpEntity<>(map, requestHeaders), String.class);
            return ResultData.success(result);
        } catch (RestClientResponseException ex) {
            rawStatusCode = ex.getRawStatusCode();
            result = ex.getResponseBodyAsString();
            ResultData<Object> errResult = new ResultData<>();
            errResult.setCode(rawStatusCode);
            errResult.setData(result);
        }
        return ResultData.error(ErrorMsgType.Fail);
    }

}
